package com.htgd.gardenexpo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.GeConFoodDao;
import com.htgd.gardenexpo.dao.WxUserCollectDao;
import com.htgd.gardenexpo.entity.CommonResult;
import com.htgd.gardenexpo.entity.GeConFood;
import com.htgd.gardenexpo.entity.GeConFoodShop;
import com.htgd.gardenexpo.dao.GeConFoodShopMapper;
import com.htgd.gardenexpo.page.FoodShopQuery;
import com.htgd.gardenexpo.service.GeBaseDictService;
import com.htgd.gardenexpo.service.IGeConFoodShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.htgd.gardenexpo.service.WxUserCollectService;
import com.htgd.gardenexpo.vo.GeConFoodShopVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

import static com.htgd.gardenexpo.utils.CalculationUtils.calculateDistance;

/**
 * <p>
 * 美食店铺表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-04-13
 */
@Service
public class GeConFoodShopServiceImpl extends ServiceImpl<GeConFoodShopMapper, GeConFoodShop> implements IGeConFoodShopService {

    @Autowired
    private GeConFoodShopMapper geConFoodShopMapper;

    @Autowired
    private GeConFoodDao geConFoodDao;

    @Autowired
    private GeBaseDictService geBaseDictService;

    @Autowired
    private WxUserCollectDao wxUserCollectDao;

    @Autowired
    private WxUserCollectService wxUserCollectService;

    @Override
    public CommonResult add(GeConFoodShop geConFoodShop) {
        geConFoodShop.setStatus("4");
        geConFoodShop.setDeleteFlag("0");
        geConFoodShopMapper.insert(geConFoodShop);
        return CommonResult.success("添加成功");
    }

    @Override
    public CommonResult edit(GeConFoodShop geConFoodShop) {
        geConFoodShopMapper.updateById(geConFoodShop);
        return CommonResult.success("编辑成功");
    }

    @Override
    public CommonResult delete(String id) {
        //获取店铺下所有美食
        List<GeConFood> geConFoods = geConFoodDao.getListByShopId(id);

        if(geConFoods.size()>0){
            return CommonResult.error("此店铺下有绑定的美食，请先删除美食!");
        }else {
            lambdaUpdate().eq(GeConFoodShop::getId,id)
                    .set(GeConFoodShop::getDeleteFlag,"1");
            return CommonResult.success("删除成功");
        }
    }

    @Override
    public CommonResult pageList(String openId, FoodShopQuery foodShopQuery) {
        if(foodShopQuery.getOrderBy()!=null && !"".equals(foodShopQuery.getOrderBy())){ //先排序 在分页
            List<GeConFoodShopVO> geConFoodShopVOS = geConFoodShopMapper.pageList(foodShopQuery);
            for (GeConFoodShopVO geConFoodShopVO : geConFoodShopVOS) {
                //分类
                if(geConFoodShopVO.getType()!=null){
                    String typeText = "";
                    String[] split = geConFoodShopVO.getType().split(",");
                    for (String s : split) {
                        String food_type = geBaseDictService.getTextByCodeAndValue("food_type", s);
                        typeText = typeText + food_type + ",";
                    }
                    geConFoodShopVO.setTypeText(typeText.substring(0,typeText.length()-1));
                }

                //经纬度
                if (foodShopQuery.getLng() != null && !foodShopQuery.getLng().isEmpty()
                        && foodShopQuery.getLat() != null && !foodShopQuery.getLat().isEmpty()
                        && geConFoodShopVO.getLng() != null && !geConFoodShopVO.getLng().isEmpty()
                        && geConFoodShopVO.getLat() != null && !geConFoodShopVO.getLat().isEmpty()) {
                    double distance = calculateDistance(foodShopQuery.getLat(), foodShopQuery.getLng(), geConFoodShopVO.getLat(), geConFoodShopVO.getLng());
                    geConFoodShopVO.setDistanceValue(distance);
                    geConFoodShopVO.setDistance(String.format("%.2f km",distance));
                }

                //热度
                long collects = wxUserCollectDao.getTypeCount("foodShop");
                long hot = geConFoodShopVO.getHit() + collects * 3 ;
                geConFoodShopVO.setHot(hot);

                //收藏
                geConFoodShopVO.setCollect(false);
                if(openId!=null){
                    Boolean collect = wxUserCollectService.isLike(openId, String.valueOf(geConFoodShopVO.getId()),"foodShop");
                    geConFoodShopVO.setCollect(collect);
                }
                //点赞数
                Long collectAmount = wxUserCollectService.getCollectAmount(String.valueOf(geConFoodShopVO.getId()),"foodShop");
                geConFoodShopVO.setCollectAmount(collectAmount);
            }

            if("distance".equals(foodShopQuery.getOrderBy())){//距离排序
                // 排序，根据计算的距离进行升序排序
                geConFoodShopVOS.sort(Comparator.comparingDouble(geConFoodShopVO ->
                        Optional.ofNullable(geConFoodShopVO.getDistanceValue()).orElse(Double.MAX_VALUE)));
            }

            if ("hot".equals(foodShopQuery.getOrderBy())) { // 热度排序
                geConFoodShopVOS.sort(Comparator.comparing(GeConFoodShopVO::getHot).reversed());
            }
            //分页
            int startIndex = (foodShopQuery.getPageNum() - 1) * foodShopQuery.getPageSize();
            int endIndex = Math.min(startIndex + foodShopQuery.getPageSize(), geConFoodShopVOS.size());
            List<GeConFoodShopVO> paginatedList = geConFoodShopVOS.subList(startIndex, endIndex);

            PageInfo<GeConFoodShopVO> list = new PageInfo<>(paginatedList);
            return CommonResult.success(String.valueOf(list.getTotal()),list.getList());

        }else {
            PageHelper.startPage(foodShopQuery.getPageNum(),foodShopQuery.getPageSize());
            List<GeConFoodShopVO> geConFoodShopVOS = geConFoodShopMapper.pageList(foodShopQuery);

            for (GeConFoodShopVO geConFoodShopVO : geConFoodShopVOS) {
                //分类
                if(geConFoodShopVO.getType()!=null){
                    String typeText = "";
                    String[] split = geConFoodShopVO.getType().split(",");
                    for (String s : split) {
                        String food_type = geBaseDictService.getTextByCodeAndValue("food_type", s);
                        typeText = typeText + food_type + ",";
                    }
                    geConFoodShopVO.setTypeText(typeText.substring(0,typeText.length()-1));
                }

                //经纬度
                if (foodShopQuery.getLng() != null && !foodShopQuery.getLng().isEmpty()
                        && foodShopQuery.getLat() != null && !foodShopQuery.getLat().isEmpty()
                        && geConFoodShopVO.getLng() != null && !geConFoodShopVO.getLng().isEmpty()
                        && geConFoodShopVO.getLat() != null && !geConFoodShopVO.getLat().isEmpty()) {
                    double distance = calculateDistance(foodShopQuery.getLat(), foodShopQuery.getLng(), geConFoodShopVO.getLat(), geConFoodShopVO.getLng());
                    geConFoodShopVO.setDistanceValue(distance);
                    geConFoodShopVO.setDistance(String.format("%.2f km",distance));
                }

                //收藏
                geConFoodShopVO.setCollect(false);
                if(openId!=null){
                    Boolean collect = wxUserCollectService.isLike(openId, String.valueOf(geConFoodShopVO.getId()),"foodShop");
                    geConFoodShopVO.setCollect(collect);
                }
                //点赞数
                Long collectAmount = wxUserCollectService.getCollectAmount(String.valueOf(geConFoodShopVO.getId()), "foodShop");
                geConFoodShopVO.setCollectAmount(collectAmount);

            }
            PageInfo<GeConFoodShopVO> list = new PageInfo<>(geConFoodShopVOS);
            return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
        }

    }

    @Override
    public CommonResult details(String openId, String id) {
        GeConFoodShopVO geConFoodShopVO = new GeConFoodShopVO();

        //浏览加1
        lambdaUpdate().setSql("hit = hit +1")
                .eq(GeConFoodShop::getId,id)
                .update();

        GeConFoodShop geConFoodShop = geConFoodShopMapper.selectById(id);
        BeanUtils.copyProperties(geConFoodShop,geConFoodShopVO);

        //美食
        List<GeConFood> listByShopId = geConFoodDao.getReleaseListByShopId(id);
        for (GeConFood geConFood : listByShopId) {
            //收藏
            geConFood.setCollect(false);
            if(openId!=null){
                Boolean collect = wxUserCollectService.isLike(openId, String.valueOf(geConFood.getId()),"food");
                geConFood.setCollect(collect);
            }
            //点赞数
            Long collectAmount = wxUserCollectService.getCollectAmount(String.valueOf(geConFood.getId()), "food");
            geConFood.setCollectAmount(collectAmount);
        }
        geConFoodShopVO.setFoods(listByShopId);


        return CommonResult.success("查询成功",geConFoodShopVO);
    }

    @Override
    public CommonResult review(GeConFoodShop geConFoodShop) {

        lambdaUpdate().eq(GeConFoodShop::getId,geConFoodShop.getId())
                .set(GeConFoodShop::getStatus,geConFoodShop.getStatus())
                .update();
        return CommonResult.success("审核成功");
    }

    @Override
    public CommonResult shopList() {
        List<GeConFoodShop> list = lambdaQuery()
                .eq(GeConFoodShop::getStatus, "3")
                .eq(GeConFoodShop::getDeleteFlag,"0")
                .list();
        return CommonResult.success("查询成功",list);
    }
}
